package com.crayfish.quduo.presenter;

import com.crayfish.quduo.base.RxPresenter;
import com.crayfish.quduo.http.JokeItemResponse;
import com.crayfish.quduo.http.RetrofitHelper;
import com.crayfish.quduo.model.JokeItemBean;
import com.crayfish.quduo.presenter.contract.JokeContract;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 作者：crayfish(徐杰)
 * 描述：
 * Created by crayfish on 2017/3/28.
 */
public class JokePresenter extends RxPresenter<JokeContract.View> implements JokeContract.Presenter {

    private RetrofitHelper mRetrofitHelper;

    public JokePresenter(RetrofitHelper retrofitHelper){
        this.mRetrofitHelper = retrofitHelper;
    }

    @Override
    public void getJokeData(int page) {
        Subscription rxSubscription = mRetrofitHelper.getJokeList(String.valueOf(page),"20","")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<JokeItemResponse<JokeItemBean>, Observable<List<JokeItemBean.Item>>>() {
                    @Override
                    public Observable<List<JokeItemBean.Item>> call(final JokeItemResponse<JokeItemBean> jokeItemResponse) {
                        if(jokeItemResponse.getShowapi_res_code() == 0){
                            return Observable.create(new Observable.OnSubscribe<List<JokeItemBean.Item>>() {
                                @Override
                                public void call(Subscriber<? super List<JokeItemBean.Item>> subscriber) {
                                    try {
                                        subscriber.onNext(jokeItemResponse.getShowapi_res_body().getContentlist());
                                        subscriber.onCompleted();
                                    } catch (Exception e) {
                                        subscriber.onError(e);
                                    }
                                }
                            });
                        }else{
                            return Observable.error(new Exception("服务器返回error"));
                        }
                    }
                })
                .subscribe(new Action1<List<JokeItemBean.Item>>() {
                    @Override
                    public void call(List<JokeItemBean.Item> jokeItemBeen) {
                        mView.showList(jokeItemBeen);
                    }
                },new Action1<Throwable>(){
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError("加载数据失败！");
                    }
                });
        addSubscribe(rxSubscription);
    }
}
